package views;

import android.content.Context;
import android.support.annotation.DrawableRes;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.zx.theline.R;

import Utils.DensityUtil;

/**
 * Created by Administrator on 2017/5/17.
 */

public class MenuItem extends RelativeLayout {

    ImageView title_image;
    TextView title_text;
    int titleImageId;
    String titleText="默认标题";
    int mWidth;
    int mHeight;
    WindowManager wm;
    DisplayMetrics dm;
    View view;

    public MenuItem(Context context,@DrawableRes int titleImageId,String titleText) {
        super(context);
        this.titleImageId=titleImageId;
        this.titleText=titleText;
        setView();
    }

    public MenuItem(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setView(){
        view=View.inflate(getContext(), R.layout.body_menu_item,null);

        title_image= (ImageView) view.findViewById(R.id.title_image);
        title_text= (TextView) view.findViewById(R.id.title_text);

        this.addView(view);


        //设置主题图片 40*40
        if(titleImageId!=0){
            title_image.setImageResource(titleImageId);
        }
        //设置标题内容
        if(titleText!=null){
            title_text.setText(titleText);
        }

        //获取windowmanager对象 获取屏幕宽度 设置item 宽度为 屏幕宽度1/3 高度为200  即每行设置三个菜单选项
        wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        dm=new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        mWidth=dm.widthPixels/3;
        mHeight=200;
        setPadding(10,10,10,10);

    }

    //绘制menuItem 宽度为 屏幕宽度1/3 每行填充三个
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        View childView = null;
        for(int i=0;i<getChildCount();i++){
             childView=getChildAt(i);
            //测量view的大小 获取measure宽度和高度 此时getwidth getheight==0 onlayout以后 getwith getheight 才有值 为view的实际宽高
            measureChild(childView,widthMeasureSpec,heightMeasureSpec);
            RelativeLayout.LayoutParams lp= (LayoutParams) childView.getLayoutParams();
            //leftmargin topmargin 分别等于 (父View值-子view值）/2
            lp.leftMargin = (mWidth-childView.getMeasuredWidth())/2;
            lp.rightMargin = (mWidth-childView.getMeasuredWidth())/2;
            lp.topMargin=(mHeight-childView.getMeasuredHeight())/2;
            lp.bottomMargin=(mHeight-childView.getMeasuredHeight())/2;
            childView.setLayoutParams(lp);
        }
        setMeasuredDimension(mWidth, getMeasuredHeight());
    }


}
